﻿using huqiang.Framework;
using huqiang.Framework.Http;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class CheckAssetsStep : AssetsAction
{
    bool start;
    string baseUrl;
    string apkPath;
    HttpDownloader apkDownload;
    enum CheckState
    {
        None,
        GetVersion,
        GetAssetsRecord,
        DownloadApk
    }

    CheckState state;
    //UnityWebRequest versionRequest;
    //long vrTime;
    public override void Reset()
    {
        start = true;
        _done = false;
#if DEBUG
        if (LocalSetting.bundleUrl==""||LocalSetting.bundleUrl==null)
        {
            Debug.Log("暂未配置资源服务器地址,请在StreamingAssets/BaseSetting.ini中配置");
            _done = true;
            return;
        }
#endif
        AssetsType = LocalSetting.platform;
        state = CheckState.GetVersion;
        baseUrl = LocalSetting.bundleUrl + AssetsType;
        string args = "?time=" + System.DateTime.Now.Ticks;
        string url = LocalSetting.versionUrl + args;

        HttpDownloader misson = new HttpDownloader();
        misson.url = url;
        misson.Completed = GetVersionCompelete;
        HFBase.GetModule<HttpManager>().AddMission(misson);
        //HttpFileManager.AddMission(misson);
    }
    void GetVersionCompelete(IMission mission)
    {
        var http = mission as HttpDownloader;
        if (http.code==200)
        {
            state = CheckState.GetAssetsRecord;
            string info = System.Text.Encoding.UTF8.GetString(http.data);
            AssetsVersion version = JsonUtility.FromJson<AssetsVersion>(info);
            LocalSetting.SetString("assets", "version", version.assversion);
            LocalSetting.assetsVersion = version.assversion;
            LocalSetting.firstPack = version.firstpack;
            if (AssetsVersionControl.CompareNumber(version.appversion, Application.version) > 0)//需要更新程序
            {
#if UNITY_ANDROID
                CheckApk(version.appversion);
                return;
#elif UNITY_IPHONE
                Debug.LogError("程序版本与记录版本不符，需要升级");
#if DEBUG
                Application.OpenURL(LocalSetting.GetString("store", "pgyer"));
#else
                Application.OpenURL(LocalSetting.GetString("store", "appstore"));
#endif
               return;
#endif
            }
            DownloadAssetsList();
        }
        else
        {
            http.Reset();
            http.url = LocalSetting.versionUrl + "?time=" + System.DateTime.Now.Ticks;
            HFBase.GetModule<HttpManager>().AddMission(http);
        }
    }
    int assCount = 0;
    /// <summary>
    /// 更新资源列表
    /// </summary>
    void DownloadAssetsList()
    {
        HttpManager manager = HFBase.GetModule<HttpManager>();
        string assName= "assets" + LocalSetting.assetsVersion + ".ini";
        string assPath = LocalSetting.RecordPath + "/" + assName;
        if (!File.Exists(assPath))
        {
            assCount++;
            manager.Download(LocalSetting.RecordPath,assName, baseUrl + "/assets" + LocalSetting.assetsVersion + ".ini"
                ,null,null,BundleCheck);
        }
        if(LocalSetting.firstPack!=null && LocalSetting.firstPack!="")
        {
            string packPath = LocalSetting.RecordPath + "/" + LocalSetting.firstPack + ".txt";
            if (!File.Exists(packPath))
            {
                manager.Download(LocalSetting.RecordPath, LocalSetting.firstPack + ".txt",
                    baseUrl + "/" + LocalSetting.firstPack + ".txt", null, null, BundleCheck);
                assCount++;
            }
        }
        if(assCount==0)
        {
            AssetsVersionControl.LoadNetVersion(assPath);
            _done = true;
        }
    }
    void BundleCheck(IMission mission)
    {
        var http = mission as HttpDownloader;
        if (http.code == 200)
        {
            assCount--;
            if (assCount <= 0)
            {
                string assPath = LocalSetting.RecordPath + "/assets" + LocalSetting.assetsVersion + ".ini";
                AssetsVersionControl.LoadNetVersion(assPath);
                _done = true; 
            }
        }
        else
        {
            http.Reset();
            HFBase.GetModule<HttpManager>().AddMission(http);
            //HttpFileManager.AddMission(http);
        }
    }
    /// <summary>
    /// 检测apk安装包，并安装
    /// </summary>
    /// <param name="version"></param>
    void CheckApk(string version)
    {
        //int appsize = AssetsVersionControl.GetAppSize();

        string apkFolder = LocalSetting.persistentDataPath + "/apks";
        if (Directory.Exists(apkFolder))
        {
            string apkFile = apkFolder + "/" + version + ".apk";
            if (File.Exists(apkFile))
            {
#if UNITY_EDITOR
                DownloadAssetsList();
                return;
#else
                int appsize = AssetsVersionControl.GetAppSize();
                 int len= (int) new FileInfo(apkFile).Length;
                if (appsize == len)
                {
                    InstallApk(apkFile);
                    return;
                }
                else File.Delete(apkFile);
#endif
            }
            else
            {
                var files = Directory.GetFiles(apkFolder);
                if (files != null)
                    for (int i = 0; i < files.Length; i++)//清除过时的apk包
                        File.Delete(files[i]);
            }
        }
        else
        {
            Directory.CreateDirectory(apkFolder);
        }
#if DEBUG
        string url = LocalSetting.baseurl + "apks/debug/" + version + ".apk";
#else
        string url = LocalSetting.baseurl+ "apks/release/" + version + ".apk";
#endif
        apkPath = apkFolder+"/"+ version + ".apk";

        HttpManager manager = HFBase.GetModule<HttpManager>();
        
        apkDownload = manager.Download(apkFolder, version + ".apk", url, "Public", version, ApkDownloadDone, 0);
        //apkDownload.BreakpointResume = true;
        state = CheckState.DownloadApk;

    }
    void ApkDownloadDone(IMission mission)
    {
        var http = mission as HttpDownloader;
        if (http.code == 200)
        {
#if UNITY_EDITOR
            DownloadAssetsList();
#else
         InstallApk(apkPath);
#endif
        }
        else
        {
            http.Reset();
            HFBase.GetModule<HttpManager>().AddMission(http);
            //HttpFileManager.AddMission(http);
        }
        //apkRequet = null;
    }
    void InstallApk(string path)
    {
        var tool = PlatformTool.Instance;
        if(tool!=null)
        {
            tool.SendString("installApk", path);
        }
    }
    public override void Update()
    {
        if(!start)
        {
            var unpack = GetStep<UnpackStep>();
            if (unpack == null)
            {
                Reset();
            }
            else if(unpack.Done)
            {
                Reset();
            }
        }
    }
    public override string Tips
    {
        get
        {
            switch(state)
            {
                case CheckState.GetVersion:
                    return "检查资源版本号";
                case CheckState.GetAssetsRecord:
                    return "获取资源记录";
                case CheckState.DownloadApk:
                    if(apkDownload!=null)
                    {
                        int a = (int)(apkDownload.Progress * 100);
                        return "正在下载App: " + a + "%";
                    }
                    else
                    {
                        return "正在下载App: 0%";
                    }
            }
            return "正在检查资源";
        }
    }
    public override float Progress 
    { 
        get
        {
            if (apkDownload != null)
            {
                return apkDownload.Progress;
            }
            return 0;
        } 
    }
}
[System.Serializable]
public class AssetsVersion
{
    public string assversion;
    public string firstpack;
    public string appversion;
    public int appsize;
    public int temp;
}
